﻿namespace ApiTemplate.WebApi
{
    /// <summary>
    /// 设置返回统一的结果
    /// </summary>
    public static class ResultSetup
    {
        /// <summary>
        /// 设置返回统一的结果
        /// </summary>
        /// <param name="services"></param>
        /// <param name="appSetting"></param>
        public static void AddResultSetup(this IServiceCollection services, AppSetting appSetting)
        {
            services.AddControllers()
           .AddNewtonsoftJson(options =>
           {
               //忽略循环引用
               options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
               if (appSetting.Naming == Naming.CamelCase)
               {
                   options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
               }
               else
               {
                   options.SerializerSettings.ContractResolver = new DefaultContractResolver();
               }
               //设置时间格式
               options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
           }); ;

            services.AddMvc(x =>
            {
                if (appSetting.CatchExcption)
                {
                    x.Filters.Add(typeof(GlobalValidationFilter));
                    x.Filters.Add(typeof(GlobalExceptionFilter)); //添加异常过滤
                }

                if (appSetting.CommonResult)
                {
                    x.Filters.Add(typeof(GlobalApiResultFilter));//返回统一的结果
                }
            });
        }
    }
}
